package com.ojoin.ojoin.eb_spider.service.catchdata.amazon;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.service.ISLDataCatchAtomStepService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

@Scope("prototype")
@Service
public class AMAZONSettlement implements
		ISLDataCatchAtomStepService<TbSlSupplyPayment> {
	private Logger log = LoggerFactory.getLogger(AMAZONSettlement.class);
	public WebDriverService webDriver;
	public TbSlPlatformUser platformUser;
	public String startTime;
	public String endTime;
	@Autowired
	private SupplyPaymentService paymentService;
	@Override
	public void get() {
		webDriver
				.get("https://vendorcentral.amazon.cn/gp/vendor/members/invoice/home?ref_=vc_ven-home_subNav");

	}

	@Override
	public void sendKeys() {

		webDriver.sendKeys("id", "sentStartDate", startTime);
		webDriver.sendKeys("id", "sentEndDate", endTime);
		// 确保invoiceStatus 元素有效，不可删除
		webDriver.findElement("id", "invoiceNumber").click();

		// 不进行条件过滤
		/*WebElement element = webDriver.waitVisibilityOfElementLocated("id",
				"invoiceStatus");

		webDriver.selectByValue(element, "INVOICE_PENDING_PAYMENT");*/

	}

	@Override
	public void submit() {
		webDriver.click("css", "#invoice-div18 > img");
	}

	@Override
	public void run() {
		get();
		sendKeys();
		submit();
	}


	private List<TbSlSupplyPayment> batchLoadRealPayCost(
			List<TbSlSupplyPayment> payments) {

		for (Iterator<TbSlSupplyPayment> ite = payments.iterator(); ite
				.hasNext();) {

			TbSlSupplyPayment entry = ite.next();
			String key = entry.getSettlementId();
			String url = entry.getMemo();

			webDriver.get(url);
			LogUtils.info(log, key);

			WebDriverWait wait = webDriver.getWebDriverWait(120);

			WebElement finalTotalCostE = null;
			long centUnit = 0;
			try {
				wait.until(ExpectedConditions
						.frameToBeAvailableAndSwitchToIt(By.id("invoiceFrame")));

				finalTotalCostE = webDriver.findElement("id","summary-tax-unit-cost-base");

				String displayTotalCost = finalTotalCostE.getText();
				String normalTotalCost = displayTotalCost.replace("￥", "")
						.replaceAll(",", "").trim();

				centUnit = NumberUtils.getLongAmount(normalTotalCost);

			} catch (Exception e) {
				try {
					WebElement mess = webDriver.findElement("css","#xDiv > div > p");
					String mes = mess.getText();
					if (!CommonUtils.isEmpty(mes)
							&& mes.contains("不再提供此发票的在线版本")) {
						long old = entry.getAmount();
						LogUtils.info(log, "key:" + key
								+ "出现一个无法获取税后金额结算单,系统默认按《A*0.75》计算");
						centUnit = old / 100 * (75);
					} else {
						throw e;
					}
				} catch (Exception e1) {
					throw e1;
				}

			}

			entry.setAmount(centUnit);

		}

		return payments;
	}

	public void result(List<TbSlSupplyPayment> unpay,List<TbSlSupplyPayment> pay) {

		List<WebElement> trs = webDriver.findElements("css",
				"table.spreadsheet tbody tr");

		for (WebElement trE : trs) {

			String IdE = webDriver.getText(trE, "css", "td:nth-of-type(2)");

			String time = webDriver
					.getText(trE, "css", "td:nth-of-type(4) div");

			String ctime = webDriver
					.getText(trE, "css", "td:nth-of-type(3) div");
			
			time = TimeUtils.getCurDate(TimeUtils.parseDate(time));
			
			ctime = TimeUtils.getCurDate(TimeUtils.parseDate(ctime));
			
			String statue = webDriver
					.getText(trE, "css", "td:nth-of-type(8) span");

			if("已注销".equals(statue)){
				continue;
			}
			WebElement totalAmountE = trE.findElement(By
					.cssSelector("td:nth-of-type(6) div"));
			WebElement realTotalAmountE = trE.findElement(By
					.cssSelector("td:nth-of-type(9) span"));

			// 抓取税后的URL
			String invoiceTaxUrl = realTotalAmountE.getAttribute("onclick")
					.replace("window.location=", "").replace("'", "")
					.replace(";", "");

			String totalAmountStr = totalAmountE.getAttribute("value");
			if ("0".equals(totalAmountStr)) {
				continue;
			}

			TbSlSupplyPayment payment = new TbSlSupplyPayment();
			payment.setPlatformAccountId(platformUser.getId());
			payment.setSettlementId(IdE);
			payment.setCreateDate(ctime);
			
			payment.setSettlementDate(time);
			long amount = NumberUtils.getLongAmount(totalAmountStr);

			payment.setAmount(amount);
			payment.setMemo(invoiceTaxUrl);
			
			if(statue.equals("已付款")){
				payment.setSettlementState(TbSlSupplyPayment.COMPLETEPAY);
				pay.add(payment);
				
			}else {
				payment.setSettlementState(TbSlSupplyPayment.WAITPAY);
				unpay.add(payment);
				
			}
			
			

			LogUtils.info(log, "对账单号：" + IdE + "\t" + "对账日期：" + time + "\t"
					+ "总金额：" + totalAmountStr);
		}
	}

	long getLongAmount(String samount) {
		long amount = -1;

		try {
			amount = -NumberUtils.getLongAmount(samount);
		} catch (Exception e) {

		}
		return amount;
	}

	public void init(WebDriverService webDriver, TbSlPlatformUser platformUser,
			String startTime, String endTime) {
		this.webDriver = webDriver;

		this.platformUser = platformUser;
		this.startTime = startTime;
		this.endTime = endTime;

	}

	@Override
	public void fiter(List<TbSlSupplyPayment> list,
			Map<String, TbSlSupplyPayment> map) {
		paymentService.removeSettlementCommon(list, map);

		batchLoadRealPayCost(list);

	}

	@Override
	public List<TbSlSupplyPayment> result() {
		// TODO Auto-generated method stub
		return null;
	}

}
